﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Collections;
using Xin478.MySocket;
using Xin478.CSWork.Common;

namespace Xin478.CSWork.Client
{
    public partial class TaskInfoCtrl : UserControl,ICorrespondable
    {
        IClient client;
        WorkInfo workInfo ;

        public TaskInfoCtrl()
        {
            InitializeComponent();
            this.Load += new EventHandler(AddTaskForm_Load);
            workInfo = new WorkInfo();
        }

        ~TaskInfoCtrl()
        {
            if (client != null) client.CommandReceived += CommandReceive;
        }

        void AddTaskForm_Load(object sender, EventArgs e)
        {
            this.fileList.DragEnter += new DragEventHandler(fileList_DragEnter);
            this.fileList.DragDrop += new DragEventHandler(fileList_DragDrop);
            this.fileList.ItemActivate += new EventHandler(fileList_ItemActivate);
            this.fileList.KeyDown += new KeyEventHandler(fileList_KeyDown);
            this.myRichEditBox1.TempAbsolutePath = UserSession.Current.TempPath;
            this.myRichEditBox1.Url ="file:\\\\\\"+ Application.StartupPath + "\\Html\\Editor.html";
            this.webBrowser1.Url=new Uri("file:\\\\\\" + Application.StartupPath + "\\Html\\CommandList.html");
            this.client.Send("User.所有用户名单");

            //接收者
            this.textBox2.Click += new EventHandler(textBox2_Click);
            //客户
            this.textBox3.TextChanged += new EventHandler(textBox3_TextChanged);
        }

        void textBox3_TextChanged(object sender, EventArgs e)
        {
            
        }

        void textBox2_Click(object sender, EventArgs e)
        {
            Point p = textBox2.PointToScreen(textBox2.Location);
            p.X -= 70;
            p.Y -= 30;
            UserListForm userListForm = new UserListForm(this.client);
            userListForm.StartPosition = FormStartPosition.Manual;
            userListForm.Location = p;
            userListForm.ShowDialog();
            EmployeeInfo ei = userListForm.ChoosedEmployeeInfo;
            if (ei != null)
            {
                textBox2.Text = ei.Name + " [" + ei.UserName + "]";
                workInfo.UserInfo = ei;
            }
        }

        void fileList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete && fileList.SelectedItems != null)
            {
                foreach (ListViewItem li in fileList.SelectedItems)
                {
                    fileList.Items.Remove(li);
                }
            }
        }

        void CommandReceive(DatagramBuilder builder, ref bool cancel)
        {
            MethodInfo mi = this.GetType().GetMethod(builder.Name, BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.Instance);
            if (mi != null)
            {
                mi.Invoke(this, builder.Params);
                cancel = true;
            }
        }

        void fileList_ItemActivate(object sender, EventArgs e)
        {
            OpenFile(fileList.FocusedItem.Tag.ToString());
        }
        void OpenFile(string filePath)
        {
            if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) return;
            try
            {
                System.Diagnostics.Process.Start(filePath);
            }
            catch { return; }
        }
        void fileList_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
        void fileList_DragDrop(object sender, DragEventArgs e)
        {
            String[] files;
            files = e.Data.GetData(DataFormats.FileDrop, false) as String[];

            foreach (string file in files)
            {
                AddFileToListView(file);
            }
        }

        void AddFileToListView(string filePath)
        {
            if (File.Exists(filePath))
            {
                Icon ico = IcoHelper.GetFileIcon(filePath, true);
                imageList1.Images.Add(ico);
                ListViewItem item = new ListViewItem();
                item.ImageIndex = imageList1.Images.Count - 1;
                item.Tag = filePath;
                filePath = filePath.Substring(filePath.LastIndexOf('\\') + 1);
                item.Text = filePath.Substring(0, filePath.LastIndexOf('.'));
                fileList.Items.Add(item);
            }
            else if (Directory.Exists(filePath))
            {
                foreach (string file in Directory.GetFiles(filePath))
                {
                    AddFileToListView(file);
                }
                foreach (string dir in Directory.GetDirectories(filePath))
                {
                    AddFileToListView(dir);
                }
            }

        }

        void AddTaskForm_Closing(object sender, CancelEventArgs e)
        {
            this.client.CommandReceived -= CommandReceive;
        }

        #region ICorrespondable 成员

        public IClient IClient
        {
            get
            {
                return this.client;
            }
            set
            {
                this.client = value;
                this.client.CommandReceived += CommandReceive;
            }
        }

        #endregion

        //添加条目
        void button3_Click(object sender, EventArgs e)
        {
            //s = Regex.Replace(s, "<p>(.*?)</p>", "$1", RegexOptions.IgnoreCase);
            //s = s.Replace("<BR>", "\r\n").Replace("&nbsp;", " ");
            string s = myRichEditBox1.HtmlText.Replace("\\","\\\\").Replace("'", "\\'");
            webBrowser1.Navigate("javascript:addItem('" + s + "');");
            myRichEditBox1.HtmlText = string.Empty;
        }

        //确认提交
        void button1_Click(object sender, EventArgs e)
        {
            if (!VerifyField()) return;

            string text = webBrowser1.Document.Body.InnerHtml.Replace("\r\n", "") ;
            Regex reg = new Regex("<div class=\"item.*?><span>(.*?)</span>.*?</div>(.*?)</div>", RegexOptions.IgnoreCase);
            Regex regimg=new Regex("<img.*?src=\"(.*?)\".*?>", RegexOptions.IgnoreCase);
            ArrayList imgList = new ArrayList();

            workInfo.Title = textBox1.Text.Trim();
            workInfo.Weight = comboBox3.SelectedIndex;
            workInfo.AddTime = DateTime.Now;
            workInfo.WorkCommandInfos = new List<WorkCommandInfo>();

            for (Match m = reg.Match(text); m.Success; m = m.NextMatch())
            {
                WorkCommandInfo cmd = new WorkCommandInfo();
                if (!string.IsNullOrEmpty(m.Groups[1].ToString()))
                    cmd.LatestTime = DateTime.Parse(m.Groups[1].ToString());

                string req=m.Groups[2].ToString();
                MatchCollection mc = regimg.Matches(req);
                foreach (Match m1 in mc)
                {
                    string s = m1.Groups[1].ToString().Trim();
                    string f = s.StartsWith("file:///") ? s.Substring(8) : s;
                    req=req.Replace(m1.Value,"<[IMG[HASHCODE="+MD5.HashFile(f)+"]]>" );
                    imgList.Add(f);
                }
                cmd.Request=req;
                workInfo.WorkCommandInfos.Add(cmd);
            }

            foreach (ListViewItem li in fileList.Items)
            {
                this.client.AddTransferFile(li.Tag.ToString(), "att?"+li.Text + "?"+workInfo.CustomerId);
            }

            foreach (object img in imgList)
            {
                this.client.AddTransferFile(img.ToString().Replace("/","\\"), "cmd");
            }
            return;
        }

        bool VerifyField()
        {
            //标题
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                textBox1.Focus();
                return false;
            }
            //接收
            if (workInfo.UserInfo == null)
            {
                textBox2.Focus();
                return false;
            }

            //客户
            if (string.IsNullOrEmpty(textBox3.Text))
            {
                textBox3.Focus();
                return false;
            }

            //优先级
            if (string.IsNullOrEmpty(comboBox3.Text))
            {
                comboBox3.DroppedDown = true;
                return false;
            }

            if (this.webBrowser1.Document.Body.Children[0].InnerHtml==null)
            {
                myRichEditBox1.Focus();
                return false;
            }

            return true;
        }

    }

    
}
